﻿module Sustainalytics.ProductInvolvement {

    import Common = Sustainalytics.Common;

    export class CompanyAssessmentService implements ICompanyAssessmentService {

        // Ctor.
        constructor(
            private $q: ng.IQService,
            private $http: ng.IHttpService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private $location: ng.ILocationService) {
        }

        private assessmentsListUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() + "/productinvolvementserv/api/v1/companyassessmentshortreports/";
        }

        private assessmentsDetailsUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() + "/productinvolvementserv/api/v1/companyassessments/";
        }

        // show error message for a given error code
        private showError(err) {
            var ctx = this;
            if (err && err['code'])
                ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode(err,  err['code']));
        }

        private showMessage(msg) {
            var ctx = this;
            ctx.notificationFactory.success(msg);
        }


        // get paged list of company assessments
        public getOwnershipValues(): ng.IPromise<string[]> {
            var ctx = this;
            var def = this.$q.defer();

            var url = ctx.assessmentsListUrl() + "/ownershipvalues";
            var promise = this.$http.get(url);

            promise.success(
                function (data) {
                    def.resolve(data);
                })
                .error(function (data, status, headers, config) {
                def.reject({ data: data, status: status, headers: headers, config: config });
            });

            return def.promise;
        }

        // get paged list of company assessments
        public getCompanyAssessments(piFilterObject: PIAssessmentListFilters, skip: number, take: number, orderBy: string[], orderByAsc: boolean, accountId: string): ng.IPromise<PIAssessmentListDto[]> {
            var ctx = this;
            var def = this.$q.defer();

            var opt = new Common.ListOptions();
            opt.skip = skip;
            opt.take = take;
            opt.orderBy = orderBy;
            opt.orderAscending = orderByAsc;
            opt.includeAllFields = true;
            opt.getCount = false;

            var params = $.param({
                filterOptions: piFilterObject,
                options: opt,
                accountId: accountId
            });

            var url = ctx.assessmentsListUrl()+ "?" + params;
            var promise = this.$http.get(url);

            promise.success(
                function (data) {
                    def.resolve(data);
                })
                .error(function (data, status, headers, config) {
                    def.reject({ data: data, status: status, headers: headers, config: config });
                });

            return def.promise;
        }

        //get count of company assessments
        public getCompanyAssessmentsCount(piFilterObject: PIAssessmentListFilters, accountId:string): ng.IPromise<number> {
            var ctx = this;
            var def = this.$q.defer();

            var options = new Common.ListOptions();
            options.getCount = true;

            var params = $.param({
                filterOptions: piFilterObject,
                options: options,
                accountId: accountId
            });

            var url = ctx.assessmentsListUrl() + "?" + params;
            var promise = this.$http.get(url);

            promise.success(
                function (res: ng.IHttpPromiseCallback<number>) {
                    def.resolve(res);
                })
                .error(function (data, status, headers, config) {
                    def.reject({ data: data, status: status, headers: headers, config: config });
                });

            return def.promise;
        }

        public getCompanyAssessmentsPagedList(piFilterObject: PIAssessmentListFilters, skip: number, take: number, orderBy: string[], orderByAsc: boolean, accountId: string): ng.IPromise<Common.PagedList<PIAssessmentListDto>> {
            var ctx = this;
            var getPromise = ctx.getCompanyAssessments(piFilterObject, skip, take, orderBy, orderByAsc, accountId);
            var getCountPromise = ctx.getCompanyAssessmentsCount(piFilterObject, accountId);
            var getPagedPromise = Common.PagedList.createPagedListFromPromises<PIAssessmentListDto>(ctx.$q, getPromise, skip, take, getCountPromise);
            return getPagedPromise;
        }

        public getCompanyAssessmentDetails(id: string): ng.IPromise<PIAssessmentDetailsDto> {

            var ctx = this;
            var def = this.$q.defer();
            
            //var promise = this.$http.get(ctx.assessmentsDetailsUrl() + id, { params: { includeAllFields: true } });
            var promise = this.$http.get(ctx.assessmentsDetailsUrl() + id);

            promise
                .success(function (data) {
                    def.resolve(data);
                })
                .error(function (data, status, headers, config) {
                    def.reject({ data: data, status: status, headers: headers, config: config });
                });

            return def.promise;
        }

        public getPIIndicators(): ng.IPromise<PIIndicatorDto[]> {

            var ctx = this;
            var def = this.$q.defer();
            var promise = this.$http.get(ctx.assessmentsDetailsUrl(), { });
            promise
                .success(data => { def.resolve(data); })
                .error(err => { ctx.showError(err); def.reject(); });
            return def.promise;
        }

        public getCompanyAssessmentReport(id: string): ng.IPromise<any> {

            var ctx = this;
            var def = this.$q.defer();
            var promise = this.$http.post(ctx.assessmentsDetailsUrl() + id + "/export", { params: {companyId: id } });

            promise
                .success(function (data) {
                    def.resolve(data);
                })
                .error(function (data, status, headers, config) {
                    def.reject({ data: data, status: status, headers: headers, config: config });
                });

            return def.promise;
        }
    }


    // register service with ProductInvolvement module
    angular.module('Sustainalytics.ProductInvolvement').service('CompanyAssessmentService',
        ['$q', '$http', 'notificationFactory', 'staticObjects', '$location', CompanyAssessmentService]);
} 